from requests import RequestException

from gis.common import track_logging
from gis.common.retry import retry
from itpay.core.mch import service as mch_service
from itpay.core.user import user_cache
from itpay.core.user.const import UserLevel
from itpay.utils import rpc

_LOGGER = track_logging.getLogger(__name__)


@retry(RequestException)
def rpc_get_user_recharge_info(mch_id, user_id):
    """
    远程调用 获取用户历史充值信息
    return: {
        'user_id'
        'level'
        'recharge_apply_count'
        'recharge_success_count'
        'recharge_success_rate'
        'recharge_success_amount'
    }
    """
    mch = mch_service.get_mch(mch_id, exclude_api_key=False)
    query_url = mch["get_charge_info_url"]
    api_key = mch["api_key"]
    params = {"user_id": user_id}
    _LOGGER.info("rpc_get_user_recharge_info params {}".format(params))
    resp_json = rpc.do_get(query_url, params, api_key)
    return resp_json["data"]


def get_user_info(mch_id, user_id):
    try:
        user = user_cache.get_user(mch_id, user_id)
        if not user:
            user = rpc_get_user_recharge_info(mch_id, user_id)
            user_cache.set_user(mch_id, user)
    except Exception:
        _LOGGER.exception("rpc get user info fail")
        return dict(user_id=user_id, level=0, recharge_success_amount=0)

    user["level"] = transform_user_level(user["recharge_success_amount"] * 100)

    # test env
    if user_id in ["1007067", "18891804"]:
        user["level"] = UserLevel.LEVEL_0.value
    if user_id in ["1002762", "18891805"]:
        user["level"] = UserLevel.LEVEL_1.value
    if user_id in ["18891707", "18891747"]:
        user["level"] = UserLevel.LEVEL_2.value
    if user_id in ["18891745"]:
        user["level"] = UserLevel.LEVEL_3.value

    return user


def transform_user_level(recharge_success_amount):
    """
    recharge_success_amount 单位是分
    免费用户：累积充值金额=0；
    普通用户：0<累积充值金额<1000；
    中级用户：1000<=累积充值金额<10000；
    高级用户：累积充值金额>=10000。
    """
    if recharge_success_amount <= 0:
        return UserLevel.LEVEL_0.value
    elif 0 < recharge_success_amount < 1_000_00:
        return UserLevel.LEVEL_1.value
    elif 1_000_00 <= recharge_success_amount < 10_000_00:
        return UserLevel.LEVEL_2.value
    else:
        return UserLevel.LEVEL_3.value
